using Pdf2epub.Interfaces;
using System.Collections.Generic;
using System.Windows;

namespace Pdf2epub.BusinessLogic
{
    internal class BulkService : CapsulingServiceBase, IBulkService
    {
        private readonly List<IBulkServiceClient> m_Clients = new List<IBulkServiceClient>();

        public bool IsActive { get; private set; }

        public void RegisterClient(IBulkServiceClient client)
        {
            if (m_Clients.Contains(client))
                return;

            m_Clients.Add(client);
        }

        public override string ToString()
        {
            if (IsActive)
                return string.Format("{0} (Active)", base.ToString());
            return string.Format("{0} (Idle)", base.ToString());
        }

        public void UnRegisterClient(IBulkServiceClient client)
        {
            if (!m_Clients.Contains(client))
                return;

            m_Clients.Remove(client);
        }

        protected override void CapsuleActivity()
        {
            IsActive = true;
        }

        protected override void UnCapsuleActivity()
        {
            IsActive = false;

            Application.Current.Dispatcher.Invoke(() =>
            {
                foreach (IBulkServiceClient client in m_Clients)
                {
                    client.ExecuteBulkReleaseAction();
                }
            });
        }
    }
}